<?php
namespace aszx0413\yii2gii\controllers;

use Yii;
use yii\web\Controller;

/**
 * 全局 HTTP 请求的基础 Controller
 */
class _Controller extends Controller
{
    public $layout = false;

    public $enableCsrfValidation = false;

    /**
     * @var int POST 或 GET 的 id
     */
    protected $reqId = 0;

    protected $globals = [];

    /**
     * @param \yii\base\Action $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }

        // --------------------------------------------------
        // 常量定义
        // --------------------------------------------------

        $routes = explode('/', Yii::$app->controller->route);
        if (count($routes) == 4) {
            define('RTD', $routes[1]);
            define('RTC', $routes[2]);
            define('RTM', $routes[3]);
        } elseif (count($routes) == 3) {
            define('RTD', $routes[0]);
            define('RTC', $routes[1]);
            define('RTM', $routes[2]);
        } else {
            define('RTD', '');
            define('RTC', $routes[0]);
            define('RTM', $routes[1]);
        }
        define('RTP', '');

        define('DATETIME', date('Y-m-d H:i:s'));

        // --------------------------------------------------
        // 初始化变量
        // --------------------------------------------------

        $this->reqId = Yii::$app->request->post('id') ?: Yii::$app->request->get('id');

        // 为了在视图中输出 POST/GET
        $this->globals['G'] = Yii::$app->request->get();
        $this->globals['P'] = Yii::$app->request->post();

        return true;
    }

    /**
     * --------------------------------------------------
     * 通用响应 HTTP 请求
     * --------------------------------------------------
     *
     * ℹ️无论是 HTML 渲染还是 JSON 返回，都共用一个方法
     */
    public function resp($data, $view)
    {
    }

    public function success()
    {
        return $this->respJson(1, '', []);
    }

    public function fail($msg, $data = null)
    {
        return $this->respJson(0, $msg, $data);
    }

    public function respJson($code, $msg, $data)
    {
        return $this->asJson([
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ]);
    }
}
